import { getOptimizedDeepSeekClient } from '@/lib/deepseek';
import { ChatMessage } from '@/types';
import { HumanMessage, SystemMessage } from '@langchain/core/messages';

/**
 * 对话摘要配置
 */
interface SummaryConfig {
  maxMessagesBeforeSummary: number;
  summaryLength: 'short' | 'medium' | 'long';
  includeContext: boolean;
  preserveImportantMessages: boolean;
}

/**
 * 对话摘要结果
 */
interface ConversationSummary {
  summary: string;
  keyPoints: string[];
  importantMessages: ChatMessage[];
  messageCount: number;
  timespan: string;
  topics: string[];
  sentiment: 'positive' | 'neutral' | 'negative';
  confidence: number;
}

/**
 * 智能对话历史摘要服务
 * 负责管理长对话的连贯性，通过智能摘要保持上下文
 */
export class ConversationSummaryService {
  private config: SummaryConfig;

  constructor(config: Partial<SummaryConfig> = {}) {
    this.config = {
      maxMessagesBeforeSummary: 20,
      summaryLength: 'medium',
      includeContext: true,
      preserveImportantMessages: true,
      ...config,
    };
  }

  /**
   * 检查是否需要生成摘要
   */
  shouldGenerateSummary(messages: ChatMessage[]): boolean {
    return messages.length >= this.config.maxMessagesBeforeSummary;
  }

  /**
   * 生成对话摘要
   */
  async generateSummary(
    messages: ChatMessage[],
    existingSummary?: ConversationSummary
  ): Promise<ConversationSummary> {
    if (messages.length === 0) {
      return this.createEmptySummary();
    }

    try {
      // 1. 预处理消息
      const processedMessages = this.preprocessMessages(messages);

      // 2. 识别重要消息
      const importantMessages =
        this.identifyImportantMessages(processedMessages);

      // 3. 提取主题和关键点
      const topics = await this.extractTopics(processedMessages);
      const keyPoints = await this.extractKeyPoints(processedMessages);

      // 4. 生成主摘要
      const summary = await this.generateMainSummary(
        processedMessages,
        existingSummary,
        topics,
        keyPoints
      );

      // 5. 分析情感倾向
      const sentiment = this.analyzeSentiment(processedMessages);

      // 6. 计算时间跨度
      const timespan = this.calculateTimespan(messages);

      // 7. 评估摘要质量
      const confidence = this.evaluateSummaryQuality(summary, messages.length);

      return {
        summary,
        keyPoints,
        importantMessages,
        messageCount: messages.length,
        timespan,
        topics,
        sentiment,
        confidence,
      };
    } catch (error) {
      console.error('生成对话摘要失败:', error);
      return this.createErrorSummary(messages);
    }
  }

  /**
   * 增量更新摘要
   */
  async updateSummary(
    existingSummary: ConversationSummary,
    newMessages: ChatMessage[]
  ): Promise<ConversationSummary> {
    if (newMessages.length === 0) {
      return existingSummary;
    }

    // 如果新消息不多，直接追加到重要消息中
    if (newMessages.length < 5) {
      const importantNewMessages = this.identifyImportantMessages(newMessages);
      return {
        ...existingSummary,
        importantMessages: [
          ...existingSummary.importantMessages.slice(-10),
          ...importantNewMessages,
        ].slice(-15),
        messageCount: existingSummary.messageCount + newMessages.length,
      };
    }

    // 否则重新生成摘要
    const allMessages = [...existingSummary.importantMessages, ...newMessages];
    return this.generateSummary(allMessages, existingSummary);
  }

  /**
   * 预处理消息
   */
  private preprocessMessages(messages: ChatMessage[]): ChatMessage[] {
    return messages
      .filter(msg => msg.content && msg.content.trim().length > 0)
      .map(msg => ({
        ...msg,
        content: msg.content.trim(),
      }));
  }

  /**
   * 识别重要消息
   */
  private identifyImportantMessages(messages: ChatMessage[]): ChatMessage[] {
    if (!this.config.preserveImportantMessages) {
      return [];
    }

    const importantMessages: ChatMessage[] = [];

    // 重要性评分标准
    const importanceKeywords = [
      '重要',
      '关键',
      '注意',
      '警告',
      '错误',
      '成功',
      '完成',
      '问题',
      '解决',
      '方案',
      '建议',
      '总结',
      '结论',
    ];

    const questionWords = ['什么', '如何', '为什么', '怎么', '能否', '可以'];

    for (const message of messages) {
      let score = 0;
      const content = message.content.toLowerCase();

      // 长度评分
      if (message.content.length > 100) score += 1;
      if (message.content.length > 200) score += 1;

      // 关键词评分
      for (const keyword of importanceKeywords) {
        if (content.includes(keyword)) score += 2;
      }

      // 问题评分
      for (const word of questionWords) {
        if (content.includes(word)) score += 1;
      }

      // 角色评分
      if (message.role === 'user') score += 1;

      // 包含代码或链接
      if (content.includes('```') || content.includes('http')) score += 1;

      if (score >= 3) {
        importantMessages.push(message);
      }
    }

    // 保留最近的重要消息
    return importantMessages.slice(-10);
  }

  /**
   * 提取对话主题
   */
  private async extractTopics(messages: ChatMessage[]): Promise<string[]> {
    if (messages.length === 0) return [];

    const conversationText = messages
      .map(msg => msg.content)
      .join(' ')
      .slice(0, 2000); // 限制长度

    const prompt = `请分析以下对话内容，提取3-5个主要话题关键词：

${conversationText}

请只返回话题关键词，用逗号分隔，不要其他解释。`;

    try {
      const client = getOptimizedDeepSeekClient('analytical');
      const response = await client.invoke([
        new SystemMessage('你是一个专业的文本分析助手，擅长提取对话主题。'),
        new HumanMessage(prompt),
      ]);

      const topicsText = response.content as string;
      return topicsText
        .split(/[,，、]/)
        .map(topic => topic.trim())
        .filter(topic => topic.length > 0)
        .slice(0, 5);
    } catch (error) {
      console.error('提取主题失败:', error);
      return ['一般对话'];
    }
  }

  /**
   * 提取关键点
   */
  private async extractKeyPoints(messages: ChatMessage[]): Promise<string[]> {
    if (messages.length === 0) return [];

    const conversationText = messages
      .map(msg => `${msg.role}: ${msg.content}`)
      .join('\n')
      .slice(0, 3000);

    const prompt = `请分析以下对话，提取3-6个关键要点：

${conversationText}

请用简洁的要点形式总结，每个要点一行，以"- "开头。`;

    try {
      const client = getOptimizedDeepSeekClient('analytical');
      const response = await client.invoke([
        new SystemMessage('你是一个专业的内容总结助手，擅长提取对话要点。'),
        new HumanMessage(prompt),
      ]);

      const keyPointsText = response.content as string;
      return keyPointsText
        .split('\n')
        .map(point => point.replace(/^-\s*/, '').trim())
        .filter(point => point.length > 0)
        .slice(0, 6);
    } catch (error) {
      console.error('提取关键点失败:', error);
      return ['对话进行中'];
    }
  }

  /**
   * 生成主摘要
   */
  private async generateMainSummary(
    messages: ChatMessage[],
    existingSummary?: ConversationSummary,
    topics: string[] = [],
    keyPoints: string[] = []
  ): Promise<string> {
    const conversationText = messages
      .map(msg => `${msg.role}: ${msg.content}`)
      .join('\n')
      .slice(0, 4000);

    let prompt = `请为以下对话生成一个${this.getSummaryLengthDescription()}的摘要：

${conversationText}`;

    if (existingSummary) {
      prompt += `\n\n之前的摘要：${existingSummary.summary}`;
      prompt += '\n\n请结合之前的摘要，生成更新的完整摘要。';
    }

    if (topics.length > 0) {
      prompt += `\n\n主要话题：${topics.join(', ')}`;
    }

    if (keyPoints.length > 0) {
      prompt += `\n\n关键要点：\n${keyPoints.map(point => `- ${point}`).join('\n')}`;
    }

    prompt += '\n\n请生成一个连贯、准确的对话摘要，保持重要信息和上下文。';

    try {
      const client = getOptimizedDeepSeekClient('conversational');
      const response = await client.invoke([
        new SystemMessage(
          '你是一个专业的对话摘要助手，能够生成准确、连贯的对话摘要。'
        ),
        new HumanMessage(prompt),
      ]);

      return (response.content as string).trim();
    } catch (error) {
      console.error('生成主摘要失败:', error);
      return this.generateFallbackSummary(messages, topics);
    }
  }

  /**
   * 分析情感倾向
   */
  private analyzeSentiment(
    messages: ChatMessage[]
  ): 'positive' | 'neutral' | 'negative' {
    const positiveWords = [
      '好',
      '棒',
      '优秀',
      '成功',
      '满意',
      '喜欢',
      '感谢',
      '完美',
    ];
    const negativeWords = [
      '坏',
      '差',
      '失败',
      '错误',
      '问题',
      '困难',
      '不满',
      '抱歉',
    ];

    let positiveScore = 0;
    let negativeScore = 0;

    const allText = messages
      .map(msg => msg.content)
      .join(' ')
      .toLowerCase();

    for (const word of positiveWords) {
      const matches = allText.match(new RegExp(word, 'g'));
      if (matches) positiveScore += matches.length;
    }

    for (const word of negativeWords) {
      const matches = allText.match(new RegExp(word, 'g'));
      if (matches) negativeScore += matches.length;
    }

    if (positiveScore > negativeScore * 1.5) return 'positive';
    if (negativeScore > positiveScore * 1.5) return 'negative';
    return 'neutral';
  }

  /**
   * 计算时间跨度
   */
  private calculateTimespan(messages: ChatMessage[]): string {
    if (messages.length === 0) return '无';

    const timestamps = messages
      .map(msg => new Date(msg.created_at).getTime())
      .filter(time => !isNaN(time))
      .sort();

    if (timestamps.length < 2) return '单次对话';

    const start = timestamps[0];
    const end = timestamps[timestamps.length - 1];
    const diffMs = end - start;

    const diffMinutes = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMinutes / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffDays > 0) return `${diffDays}天`;
    if (diffHours > 0) return `${diffHours}小时`;
    if (diffMinutes > 0) return `${diffMinutes}分钟`;
    return '几秒钟';
  }

  /**
   * 评估摘要质量
   */
  private evaluateSummaryQuality(
    summary: string,
    messageCount: number
  ): number {
    let score = 0.5; // 基础分数

    // 长度评分
    if (summary.length > 50) score += 0.1;
    if (summary.length > 100) score += 0.1;
    if (summary.length > 200) score += 0.1;

    // 内容质量评分
    if (summary.includes('对话') || summary.includes('讨论')) score += 0.1;
    if (summary.includes('用户') || summary.includes('助手')) score += 0.1;

    // 消息数量评分
    if (messageCount > 10) score += 0.1;
    if (messageCount > 20) score += 0.1;

    return Math.min(score, 1.0);
  }

  /**
   * 获取摘要长度描述
   */
  private getSummaryLengthDescription(): string {
    switch (this.config.summaryLength) {
      case 'short':
        return '简短';
      case 'long':
        return '详细';
      default:
        return '中等长度';
    }
  }

  /**
   * 生成备用摘要
   */
  private generateFallbackSummary(
    messages: ChatMessage[],
    topics: string[]
  ): string {
    const userMessages = messages.filter(msg => msg.role === 'user').length;
    const assistantMessages = messages.filter(
      msg => msg.role === 'assistant'
    ).length;

    let summary = `这是一段包含${messages.length}条消息的对话，`;
    summary += `其中用户发送了${userMessages}条消息，助手回复了${assistantMessages}条消息。`;

    if (topics.length > 0) {
      summary += `主要讨论了${topics.join('、')}等话题。`;
    }

    return summary;
  }

  /**
   * 创建空摘要
   */
  private createEmptySummary(): ConversationSummary {
    return {
      summary: '暂无对话内容',
      keyPoints: [],
      importantMessages: [],
      messageCount: 0,
      timespan: '无',
      topics: [],
      sentiment: 'neutral',
      confidence: 0,
    };
  }

  /**
   * 创建错误摘要
   */
  private createErrorSummary(messages: ChatMessage[]): ConversationSummary {
    return {
      summary: `对话摘要生成失败，共${messages.length}条消息`,
      keyPoints: ['摘要生成出现错误'],
      importantMessages: messages.slice(-3),
      messageCount: messages.length,
      timespan: this.calculateTimespan(messages),
      topics: ['未知'],
      sentiment: 'neutral',
      confidence: 0.1,
    };
  }

  /**
   * 格式化摘要用于显示
   */
  formatSummaryForDisplay(summary: ConversationSummary): string {
    let formatted = `📝 **对话摘要** (${summary.messageCount}条消息，${summary.timespan})\n\n`;
    formatted += `${summary.summary}\n\n`;

    if (summary.topics.length > 0) {
      formatted += `🏷️ **主要话题**: ${summary.topics.join(', ')}\n\n`;
    }

    if (summary.keyPoints.length > 0) {
      formatted += `🔑 **关键要点**:\n${summary.keyPoints.map(point => `• ${point}`).join('\n')}\n\n`;
    }

    const sentimentEmoji = {
      positive: '😊',
      neutral: '😐',
      negative: '😔',
    };

    formatted += `${sentimentEmoji[summary.sentiment]} **情感倾向**: ${summary.sentiment}`;

    return formatted;
  }
}

// 导出单例实例
export const conversationSummaryService = new ConversationSummaryService();

// 导出类型
export type { ConversationSummary, SummaryConfig };
